﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.IO;
using System.Collections;
using Newtonsoft.Json.Linq;

namespace BEX.Core.Exchange.TRADEHILL
{
    public class Tradehill : Exchange
    {
        public Tradehill()
            : base(ExchangeType.TRADEHILL)
        {
            
        }

        internal override Tick GetCurrentTick(CurrencyPair pair)
        {
            TradehillResponse response = GetTradehillTick(pair);

            Tick res = new Tick();

            res.Ask = Convert.ToInt32(response.returnType.ask.value_int);
            res.Bid = Convert.ToInt32(response.returnType.bid.value_int);
            res.Currency = pair;
            res.ExchangeSource = ExchangeType.TRADEHILL;
            res.Time = DateTime.UtcNow;
            res.Spot = Convert.ToInt32(response.returnType.last.value_int);

            return res;
        }

        private TradehillResponse GetTradehillTick(CurrencyPair pair)
        {
            //https://tradehill.com/mtgapi/BTCUSD/ticker
            var queryStr = string.Format(TickerURL, pair.Base.ToString(), pair.Counter.ToString());
            var resp = Query(queryStr);
            return new TradehillResponse(JObject.Parse(resp) as JObject);
        }

        private static string Query(string url)
        {
            var request = WebRequest.Create(url);
            request.Method = "GET";
            if (request == null)
            {
                throw new Exception("Non HTTP WebRequest");
            }
            return new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd();
        }


        protected override string _baseUrl
        {
            get { return ExchangeConfig.Default.TradehillAPI_BaseURL; }
        }

        protected override string _tickPath
        {
            get { return ExchangeConfig.Default.TradehillAPI_GetTickPath; }
        }

        protected override string _pairs
        {
            get { return ExchangeConfig.Default.Tradehill_Pairs; }
        }

    }
}
